package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import config.ProducerConsumerConfig;
import config.direct.DirectRoutingKeyEnum;
import po.Mail;
import po.TopicMail;
import service.impl.ProducerImpl;
import service.impl.PublisherImpl;

@Controller
public class RabbitMQController {

	@Autowired
	ProducerImpl producer;

	@Autowired
	PublisherImpl publisher;


	/**
	 * 使用direct交换机发送消息
	 * 
	 * routingKey需存在DirectRoutingKeyEnum中，不存在消息会被抛弃，对routingKey使用枚举做了限制
	 * 
	 * @param mail
	 */
	@RequestMapping(value = "/direct", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String direct(@ModelAttribute("mail") TopicMail mail) {
		Mail m = new Mail(mail.getMailId(), mail.getCountry(), mail.getWeight());
		publisher.sendDirectMail(m, DirectRoutingKeyEnum.valueOf(mail.getRoutingKey()));
		return "success";
	}
	
	/**
	 * 自定义queue，direct的精简模式，去除Exchange配置
	 * 
	 * @param mail
	 * @throws Exception
	 */
	@RequestMapping(value = "/produce", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public void produce(@ModelAttribute("mail") Mail mail) throws Exception {
		producer.sendMail(ProducerConsumerConfig.QUERY_NAME, mail);
	}
	

	/**
	 * 使用fanout(发布订阅模式)交换机发布消息给所有队列
	 * 
	 * @param mail
	 * @throws Exception
	 */
	@RequestMapping(value = "/fanout", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public void fanout(@ModelAttribute("mail") Mail mail) throws Exception {
		publisher.publishMail(mail);
	}

	/**
	 * 使用topic交换机发送消息
	 * 
	 * @param mail
	 */
	@RequestMapping(value = "/mytopic", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public void topic(@ModelAttribute("mail") TopicMail mail) {
		Mail m = new Mail(mail.getMailId(), mail.getCountry(), mail.getWeight());
		publisher.sendtopicMail(m, mail.getRoutingKey());
	}

}
